package com.wannengbang.cloudleader.performance;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseFragment;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.StatisticsBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.UpDateNameEvent;
import com.wannengbang.cloudleader.homepage.AgentAllListActivity;
import com.wannengbang.cloudleader.homepage.AgentStandardListActivity;
import com.wannengbang.cloudleader.homepage.MerchantInfoListActivity;
import com.wannengbang.cloudleader.homepage.TransactionQueryActivity;
import com.wannengbang.cloudleader.performance.model.IPerformanceModel;
import com.wannengbang.cloudleader.performance.model.PerformanceModelImpl;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.widget.AppTitleBar;

import org.greenrobot.eventbus.Subscribe;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 业绩
 */
public class PerformanceFragment extends BaseFragment {


    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_order_fee_count_total)
    TextView tvOrderFeeCountTotal;
    @BindView(R.id.tv_look_details)
    TextView tvLookDetails;
    @BindView(R.id.tv_agent_count)
    TextView tvAgentCount;
    @BindView(R.id.ll_agent)
    LinearLayout llAgent;
    @BindView(R.id.tv_order_count)
    TextView tvOrderCount;
    @BindView(R.id.ll_order_count)
    LinearLayout llOrderCount;
    @BindView(R.id.tv_order_fee_count)
    TextView tvOrderFeeCount;
    @BindView(R.id.ll_transaction)
    LinearLayout llTransaction;
    @BindView(R.id.tv_device_activation_num)
    TextView tvDeviceActivationNum;
    @BindView(R.id.ll_device_activation_num)
    LinearLayout llDeviceActivationNum;
    @BindView(R.id.tv_today_agent_count)
    TextView tvTodayAgentCount;
    @BindView(R.id.tv_standard_agent_count)
    TextView tvStandardAgentCount;
    @BindView(R.id.ll_standard_agent)
    LinearLayout llStandardAgent;
    @BindView(R.id.ll_today_agent)
    LinearLayout llTodayAgent;
    private IPerformanceModel performanceModel;
    private UserInfoBean userInfoBean;
    private BottomSheetDialog selectPicDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_performance, container, false);
        ButterKnife.bind(this, view);
        initView();
        registerEventBus();
        return view;
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();
    }

    public void initView() {
        performanceModel = new PerformanceModelImpl();
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null && userInfoBean.getData() != null) {
            tvName.setText(userInfoBean.getData().getName());

            //6标记隐藏
            if ("17329409714".equals(userInfoBean.getData().getMobile()) || "13403854628".equals(userInfoBean.getData().getMobile())) {
                llDeviceActivationNum.setVisibility(View.GONE);
            } else {
                llDeviceActivationNum.setVisibility(View.VISIBLE);
            }
        }
        titleBar.setRightClickListener(() -> {
            showPictureSelectorDialog();
        });
        requestData();
    }

    @Subscribe
    public void onUpDateNameEvent(UpDateNameEvent event) {
        if (userInfoBean != null && userInfoBean.getData() != null) {
            userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
            tvName.setText(userInfoBean.getData().getName());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestData();
    }

    private void showPictureSelectorDialog() {
        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);
        album.setText("按日查询");
        camera.setText("按月查询");
        album.setOnClickListener(v -> {
            Intent intent = new Intent(mActivity, PerformanceQueryActivity.class);
            intent.putExtra("cycleType", "date");
            intent.putExtra("param", DateTimeUtil.getToDayDate2());
            startActivity(intent);
            cancelPictureDialog();
        });
        camera.setOnClickListener(v -> {
            Intent intent = new Intent(mActivity, PerformanceQueryActivity.class);
            intent.putExtra("cycleType", "month");
            intent.putExtra("param", DateTimeUtil.getMonthDate2());
            startActivity(intent);
            cancelPictureDialog();
        });
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestData();
        }
    }

    public void requestData() {
        performanceModel.requestLineStatistics("", "", new DataCallBack<StatisticsBean>() {
            @Override
            public void onSuccessful(StatisticsBean bean) {
                String orderFeeCountTotal = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(bean.getData().getNew_order_sum()) / 100);
                tvOrderFeeCountTotal.setText(orderFeeCountTotal);
                tvAgentCount.setText(bean.getData().getNew_agent_count());
                tvOrderCount.setText(bean.getData().getNew_order_count());
                String orderFeeCount = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(bean.getData().getNew_order_sum()) / 100);
                tvOrderFeeCount.setText(orderFeeCount);
                tvDeviceActivationNum.setText(bean.getData().getDevice_activation_num());
                tvTodayAgentCount.setText(bean.getData().getNew_agent_count_today());
                tvStandardAgentCount.setText(bean.getData().getStandard_count());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @OnClick({R.id.tv_look_details, R.id.ll_agent, R.id.ll_standard_agent, R.id.ll_today_agent, R.id.ll_order_count, R.id.ll_transaction, R.id.ll_device_activation_num})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_look_details:
                Intent intent = new Intent(mActivity, TransactionQueryActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
            case R.id.ll_agent:
                intent = new Intent(mActivity, AgentAllListActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
            case R.id.ll_standard_agent:
                intent = new Intent(mActivity, AgentStandardListActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
            case R.id.ll_today_agent:
                intent = new Intent(mActivity, AgentAllListActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", DateTimeUtil.format(new Date()));
                startActivity(intent);
                break;
            case R.id.ll_order_count:
                intent = new Intent(mActivity, TransactionQueryActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
            case R.id.ll_transaction:
                intent = new Intent(mActivity, PerformanceTypeActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
            case R.id.ll_device_activation_num:
                intent = new Intent(mActivity, MerchantInfoListActivity.class);
                intent.putExtra("cycleType", "all");
                intent.putExtra("param", "2018-01-01");
                startActivity(intent);
                break;
        }
    }

}
